<template>
  <div class="chat-view">
    <!-- 聊天头部（返回 + 对方信息） -->
    <div class="chat-header">
      <button class="back-btn" @click="router.back()">
        ← 返回
      </button>
      <div class="user-info">
        <img 
          :src="currentUser?.avatarUrl || '/default-avatar.png'" 
          alt="用户头像" 
          class="avatar"
        >
        <span class="nickname">{{ currentUser?.nickname || '未知用户' }}</span>
      </div>
    </div>
    
    <!-- 聊天消息列表 -->
    <div class="chat-messages" ref="messagesContainer">
      <div v-if="isLoading" class="loading-state">
        <div class="spinner"></div>
      </div>
      
      <div v-else-if="chatHistory.length > 0" class="messages-container">
        <div 
          v-for="(message, index) in chatHistory" 
          :key="message.id || index"
          class="message-item"
          :class="{ 'sent': isSentMessage(message), 'received': !isSentMessage(message) }"
        >
          <img 
            :src="getMessageSenderAvatar(message)" 
            alt="头像" 
            class="message-avatar"
          >
          <div class="message-bubble">
            <p class="message-content">{{ message.content }}</p>
            <p class="message-time">{{ formatTime(message.createdAt) }}</p>
          </div>
        </div>
      </div>
      
      <div v-else class="empty-state">
        <p>开始聊天吧～</p>
      </div>
    </div>
    
    <!-- 消息输入框 -->
    <div class="chat-input">
      <textarea
        v-model="inputContent"
        class="input-area"
        placeholder="输入消息..."
        @keydown.enter.prevent="sendMessage()"
      ></textarea>
      <button 
        class="send-btn"
        :disabled="!inputContent.trim() || isSending"
        @click="sendMessage()"
      >
        发送
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import { useChatStore } from '@/store/chat'
// 移除 useUserStore 依赖，直接用 auth API 获取对方用户信息
import { getCurrentUser } from '@/api/auth'

// 状态管理
const authStore = useAuthStore()
const chatStore = useChatStore()
const router = useRouter()
const route = useRoute()

// 路由参数：对方用户ID（处理无效数字情况）
const otherUserId = ref(() => {
  const id = Number(route.params.userId)
  return isNaN(id) ? null : id
})

// 响应式数据
const inputContent = ref('')
const isSending = ref(false)
const messagesContainer = ref(null)
// 存储对方用户信息（替代 userStore）
const currentUser = ref({})

// 计算属性
const chatHistory = computed(() => {
  return chatStore.chatHistory[otherUserId.value]?.messages || []
})
const isLoading = computed(() => chatStore.isLoading)

// 生命周期：初始化
onMounted(async () => {
  // 未登录或对方ID无效 → 跳转到聊天列表
  if (!authStore.isAuthenticated || !otherUserId.value) {
    router.push('/chats')
    return
  }

  try {
    // 1. 获取对方用户信息（直接调用 auth API，无需 userStore）
    const userData = await getCurrentUser(otherUserId.value)
    currentUser.value = userData || {}

    // 2. 获取与对方的聊天历史
    await chatStore.fetchChatHistory(otherUserId.value)

    // 3. 设置当前聊天对象（用于标记已读等逻辑）
    chatStore.setCurrentChatUserId(otherUserId.value)

    // 4. 滚动到最新消息
    scrollToBottom()
  } catch (error) {
    console.error('聊天页面初始化失败：', error)
    router.push('/chats')
  }
})

// 监听聊天历史变化 → 自动滚动到底部
watch(chatHistory, () => {
  scrollToBottom()
})

// 发送聊天消息（通过 WebSocket）
const sendMessage = async () => {
  const content = inputContent.value.trim()
  // 空消息不发送
  if (!content || !otherUserId.value) return

  isSending.value = true
  try {
    // 调用 ChatStore 发送消息（内部已集成 WebSocket）
    const sendSuccess = await chatStore.sendChatMessage(otherUserId.value, content)
    // 发送成功 → 清空输入框
    if (sendSuccess) {
      inputContent.value = ''
    }
  } catch (error) {
    console.error('发送消息失败：', error)
  } finally {
    isSending.value = false
  }
}

// 工具方法：判断是否为当前用户发送的消息
const isSentMessage = (message) => {
  return message.senderId === authStore.user?.id
}

// 工具方法：获取消息发送者的头像
const getMessageSenderAvatar = (message) => {
  // 自己发送的消息 → 用自己的头像
  if (isSentMessage(message)) {
    return authStore.user?.avatarUrl || '/default-avatar.png'
  }
  // 对方发送的消息 → 用对方的头像
  return currentUser.value.avatarUrl || '/default-avatar.png'
}

// 工具方法：滚动到最新消息
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 工具方法：格式化消息时间（例：14:30）
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const time = new Date(timestamp)
  // 只显示小时和分钟（补零，如 09:05 而非 9:5）
  return time.toLocaleTimeString([], { 
    hour: '2-digit', 
    minute: '2-digit',
    hour12: false // 24小时制
  })
}
</script>

<style scoped>
.chat-view {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 600px;
  margin: 0 auto;
  background: #fafafa;
}

.chat-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.back-btn {
  padding: 8px;
  background: transparent;
  border: none;
  font-size: 16px;
  cursor: pointer;
  color: #333;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.nickname {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  /* 优化滚动体验 */
  scroll-behavior: smooth;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px;
}

.spinner {
  width: 24px;
  height: 24px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #66D7D2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.messages-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message-item {
  display: flex;
  max-width: 70%;
  align-items: flex-end; /* 消息气泡底部对齐 */
}

.message-item.sent {
  flex-direction: row-reverse;
  margin-left: auto;
}

.message-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.message-item.sent .message-avatar {
  margin-left: 8px;
}

.message-item.received .message-avatar {
  margin-right: 8px;
}

.message-bubble {
  padding: 10px 14px;
  border-radius: 18px;
  position: relative;
  max-width: calc(100% - 40px); /* 减去头像宽度 */
}

.message-item.sent .message-bubble {
  background: #66D7D2;
  color: white;
  border-bottom-right-radius: 4px;
}

.message-item.received .message-bubble {
  background: white;
  color: #333;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border-bottom-left-radius: 4px;
}

.message-content {
  margin: 0 0 4px 0;
  line-height: 1.4;
  word-wrap: break-word; /* 长文本换行 */
}

.message-time {
  margin: 0;
  font-size: 12px;
  opacity: 0.8;
  text-align: right;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px;
  color: #999;
  font-size: 14px;
}

.chat-input {
  display: flex;
  gap: 8px;
  padding: 12px 16px;
  background: white;
  box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.1);
}

.input-area {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #eee;
  border-radius: 24px;
  resize: none;
  font-size: 14px;
  min-height: 48px;
  max-height: 120px;
  /* 禁止横向滚动 */
  overflow-x: hidden;
  word-wrap: break-word;
}

.input-area:focus {
  outline: none;
  border-color: #66D7D2;
}

.send-btn {
  padding: 0 16px;
  background: #66D7D2;
  color: white;
  border: none;
  border-radius: 24px;
  cursor: pointer;
  white-space: nowrap;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 适配移动端 */
@media (max-width: 375px) {
  .chat-messages {
    padding: 12px 8px;
  }
  .message-bubble {
    padding: 8px 12px;
  }
  .input-area {
    padding: 10px 14px;
  }
}
</style>